package meta

import (
	"fmt"
	"game/game-design-v.xnanz/loader"
	"strings"
)

// 配置表宏定义格式说明
// #name name
// #unique field
// #index field field ...
// #collector field field ...
// #const key_field type_field value_field [comment_field]
type DesignClassMeta struct {
	//文件名
	FileName string
	//表格名字
	Name string
	//索引列表
	Indexes []*IndexMeta
	//分组索引列表
	Collectors []*CollectorMeta
	//字段列表
	Columns []*ColumnMeta
	//字段名字的映射
	ColumnsMap map[string]*ColumnMeta
	//字典描述元数据
	Dictionary *DictionaryMeta
	//字典列表
	Dictionaries []*DictionaryData
}

func Build(designFile *loader.DesignFile) *DesignClassMeta {
	var classMeta DesignClassMeta
	dotIndex := strings.LastIndex(designFile.Name, ".")
	classMeta.FileName = designFile.Name[:dotIndex]
	classMeta.Name = designFile.ClassName
	//构建字段的元数据
	classMeta.ColumnsMap = make(map[string]*ColumnMeta)
	for _, v := range designFile.Fields {
		columnMeta := NewColumnMeta(v)
		classMeta.Columns = append(classMeta.Columns, columnMeta)
		classMeta.ColumnsMap[columnMeta.name] = columnMeta
	}

	for _, v := range designFile.Macros {
		if strings.HasPrefix(v, "#name") || v == "#" {
			//不需要处理
		} else if strings.HasPrefix(v, "#index unique") {
			parts := strings.Split(v, " ")
			classMeta.Indexes = append(classMeta.Indexes, NewIndexMeta(parts[2:]))

		} else if strings.HasPrefix(v, "#index complex") {
			parts := strings.Split(v, " ")
			classMeta.Indexes = append(classMeta.Indexes, NewIndexMeta(parts[2:]))

		} else if strings.HasPrefix(v, "#index multiple") {
			parts := strings.Split(v, " ")
			classMeta.Collectors = append(classMeta.Collectors, NewCollectorMeta(parts[2:]))

		} else if strings.HasPrefix(v, "#index mulcom ") {
			parts := strings.Split(v, " ")
			classMeta.Collectors = append(classMeta.Collectors, NewCollectorMeta(parts[2:]))

		} else if strings.HasPrefix(v, "#const") || strings.HasPrefix(v, "#dictionary") {
			//TODO 可以考虑做成有多个字典定义
			classMeta.Dictionary = NewDictionaryMeta(v)
			//TODO 填充字典数据
			keyIndex := -1
			typeIndex := -1
			commentIndex := -1

			for i, v := range designFile.Fields {
				if v.FieldName == classMeta.Dictionary.Key() {
					keyIndex = i
				}
				if v.FieldName == classMeta.Dictionary.Form() {
					typeIndex = i
				}
				if v.FieldName == classMeta.Dictionary.Comment() {
					commentIndex = i
				}
			}
			if keyIndex < 0 || typeIndex < 0 {
				continue
			}
			for _, v := range designFile.Datas {
				if commentIndex < 0 {
					dictionaryData := OfDictionaryData(v[keyIndex], v[typeIndex], "")
					classMeta.Dictionaries = append(classMeta.Dictionaries, dictionaryData)
				} else {
					dictionaryData := OfDictionaryData(v[keyIndex], v[typeIndex], v[commentIndex])
					classMeta.Dictionaries = append(classMeta.Dictionaries, dictionaryData)
				}
			}
		} else if strings.HasPrefix(v, "#export") {

		} else if v == "" {
		} else {
			fmt.Printf("这是什么？%v\n", v)
		}
	}
	return &classMeta
}
